//AjaxUpload <?php
/*
 * Ajax File Upload, by Olivier St-Laurent
 * Version 1.1
 *
 * Basic Drag-Drop support (For Google Chrome)
 * Can upload very large files > 10GB+ (Google Chrome Only)
 *
 */
/**** HTML ****

 <div ondragover="dragUploadHover(this, event);"
 ondragleave="dragUploadOut(this, event);"
 ondrop="dropUploadFile(this, event, 'upload.php');">
 <input type="file" multiple="multiple" onchange="dropUploadFile(this, event, 'upload.php');" />
 </div>

 <script type="text/javascript">
 function dragUploadHover(elem, event) {
 // Set Hover style here

 event.stopPropagation();
 event.preventDefault();
 }
 function dragUploadOut(elem, event) {
 // Remove Hover style here

 }
 function dropUploadFile(elem, event, url) {
 dragUploadOut(elem, event);
 ajaxUpload(url, event,
 function(percent){
 // Set Uploading Percent
 console.log('Uploading... ' + percent + '%');

 }, function(response){
 // For Each Completed

 }, function(){
 // Complete
 console.log('Upload Complete!');

 }, function(errorMessage){
 // Error
 console.log('An error occured : ' + errorMessage);

 }
 );
 event.stopPropagation();
 event.preventDefault();
 }
 </script>

 */
/**** PHP (upload.php) ****

 // Using XenonPHP :

 FileUpload::simpleUpload($outputFile, 4096);

 // To Get Original name, size and type :
 FileUpload::getFileName();
 FileUpload::getFileSize();
 FileUpload::getFileType();

 // Then for resizing :
 ImageResize::simpleCopyResize($outputFile, "NewDestinationFile", 100, 100); // reduce size to maximum 100x100


 // Without XenonPHP :

 $outputFile = "uploaded_file_output_path";
 $upload = fopen("php://input", "r");
 $firstBunch = fread($upload, 4096);
 if (strlen($firstBunch) > 0) {
 file_put_contents($outputFile, $firstBunch);
 while (!feof($upload)) {
 file_put_contents($outputFile, fread($upload, 4096), FILE_APPEND);
 }
 }
 fclose($upload);

 // To Get Original name, size and type :
 $_SERVER['HTTP_X_FILE_NAME']
 $_SERVER['HTTP_X_FILE_SIZE']
 $_SERVER['HTTP_X_FILE_TYPE']
 */
//?>

function ajaxUpload(url, fileObject, progressCallback, forEachCallback, completeCallback, errorCallback, maxFiles, sync) {
    if (typeof fileObject === 'string') {
        fileObject = document.getElementById(fileObject);
    }
    var fileList = fileObject.dataTransfer || fileObject.target || fileObject;
    fileList = fileList.files || fileList || [];
    if (fileList[0] === undefined && typeof fileList === 'object' && fileList.length > 0) {
        fileList = [fileList];
    }

    if (fileList.length > 0 && (!maxFiles || fileList.length <= maxFiles)) {
        var startAjaxUpload = function(i) {
            var fileToUpload = fileList[i];
            if (fileToUpload.type !== '') {
                var xhr = new XMLHttpRequest();
                var uploadStatus = xhr.upload;
                if (typeof progressCallback === 'function') {
                    uploadStatus.addEventListener("progress", function(ev) {
                        if (ev.lengthComputable) {
                            progressCallback(parseInt(
                                ((ev.loaded / ev.total) * 100 / fileList.length) +
                                (i * (100 / fileList.length))
                                ));
                        }
                    }, false);
                }
                if (errorCallback !== undefined) {
                    uploadStatus.addEventListener("error", function(ev) {
                        errorCallback('Error while uploading.');
                        console.log(ev);
                    }, false);
                }

                xhr.onreadystatechange = function() {
                    if (xhr.readyState == 1) {
                        // Connection Initiated

                    }
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200) {
                            // Server Response Received
                            if (typeof forEachCallback === 'function') {
                                forEachCallback(xhr.responseText);
                            }
                        } else {
                            if (xhr.status == 0) {
                                // Connection Error
                                if (typeof errorCallback === 'function') {
                                    errorCallback('Connection error');
                                }
                            }
                        }
                    }
                };

                if (i + 1 < fileList.length) {
                    uploadStatus.addEventListener("load", function(ev) {
                        startAjaxUpload(i + 1);
                    }, false);
                } else {
                    if (completeCallback !== undefined) {
                        uploadStatus.addEventListener("load", function(ev) {
                            completeCallback(ev);
                        }, false);
                    }
                }
                xhr.open("POST", url, sync ? false : true);
                xhr.setRequestHeader("Cache-Control", "no-cache");
                xhr.setRequestHeader("Content-Type", "multipart/form-data");
                xhr.setRequestHeader("X-REQUESTED-WITH", "xmlhttprequest");
                xhr.setRequestHeader("X-File-Name", fileToUpload.name);
                xhr.setRequestHeader("X-File-Size", fileToUpload.size);
                xhr.setRequestHeader("X-File-Type", fileToUpload.type);
                xhr.send(fileToUpload);
            } else {
                if (i + 1 < fileList.length) {
                    startAjaxUpload(i + 1);
                } else {
                    completeCallback(null);
                }
            }
        };
        startAjaxUpload(0);
    } else {
        // Too Many Files
        if (typeof errorCallback === 'function') {
            if (maxFiles) {
                if (maxFiles === 1) {
                    errorCallback('You must select only one file');
                } else {
                    errorCallback('You must select up to ' + maxFiles + ' files.');
                }
            } else {
                errorCallback('You must select files');
            }
        }
    }
}
